package com.zys.http.extension.completion;


import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionProvider;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.json.codeinsight.JsonCompletionContributor;
import com.intellij.json.psi.JsonArray;
import com.intellij.json.psi.JsonProperty;
import com.intellij.json.psi.JsonStringLiteral;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import com.zys.http.tool.Placeholder;
import com.zys.http.ui.icon.HttpIcons;
import org.jetbrains.annotations.NotNull;

import java.util.HashSet;
import java.util.Set;

import static com.intellij.patterns.PlatformPatterns.psiElement;

/**
 * @author zys
 * @since 2025-08-17
 */
public class HttpJsonCompletionContributor extends JsonCompletionContributor {
    private static final PsiElementPattern.Capture<PsiElement> AFTER_COLON_IN_PROPERTY = psiElement()
            .afterLeaf(":").withSuperParent(2, JsonProperty.class)
            .andNot(psiElement().withParent(JsonStringLiteral.class));

    private static final PsiElementPattern.Capture<PsiElement> AFTER_COMMA_OR_BRACKET_IN_ARRAY = psiElement()
            .afterLeaf("[", ",").withSuperParent(2, JsonArray.class)
            .andNot(psiElement().withParent(JsonStringLiteral.class));

    public HttpJsonCompletionContributor() {
        extend(CompletionType.BASIC, AFTER_COLON_IN_PROPERTY, HttpJsonKeywordsCompletionProvider.INSTANCE);
        extend(CompletionType.BASIC, AFTER_COMMA_OR_BRACKET_IN_ARRAY, HttpJsonKeywordsCompletionProvider.INSTANCE);
    }


    private static final class HttpJsonKeywordsCompletionProvider extends CompletionProvider<CompletionParameters> {
        private static final HttpJsonKeywordsCompletionProvider INSTANCE = new HttpJsonKeywordsCompletionProvider();
        private static final String[] KEYWORDS ;
        static {
            Set<String> keywords = new HashSet<>(Placeholder.keywords());
            keywords.add("null");
            keywords.add("true");
            keywords.add("false");
            KEYWORDS = keywords.toArray(new String[0]);
        }

        @Override
        protected void addCompletions(@NotNull CompletionParameters parameters,
                                      @NotNull ProcessingContext context,
                                      @NotNull CompletionResultSet result) {
            for (String keyword : KEYWORDS) {
                result.addElement(LookupElementBuilder.create(keyword).withIcon(HttpIcons.PLUGIN_ICON).bold());
            }
        }
    }
}
